<template>
  <el-dialog append-to-body :visible.sync="dialog" :title="isAdd ? '新增' : (isView ? '详情' : '编辑')" width="940px">
    <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="125px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="报修时间" prop="reportTime">
            <el-date-picker
              v-model="form.reportTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择报修时间"
              style="width: 300px"
              :disabled="isView"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-select v-model="form.customerName" default-first-option placeholder="请选择客户" :disabled="isView" class="input_text" @change="handleSelect($event)">
              <el-option v-for="(item,index) in customerItem" :key="item.id + index" :label="item.customerName" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="报修设备" prop="faultDevice">
            <el-select v-model="form.faultDevice" class="input_text" placeholder="请选择" :disabled="isView" @change="handleSelectDevice">
              <el-option
                v-for="(item, index) in devices"
                :key="item.eqptname + index"
                :label="item.eqptname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="要求到场时间">
            <el-date-picker
              v-model="form.reqiureTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择到场时间"
              style="width: 300px"
              :disabled="isView"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="报修地区">
            <AreaSelect ref="areaSelect" :default-props="form" :disabled="isView" @change="handleSelectArea" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报修地址" prop="address">
            <el-input v-model="form.address" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="故障描述" prop="faultDesc">
            <el-input v-model="form.faultDesc" style="width: 760px;" :rows="4" type="textarea" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="故障图片">
            <div style="display: inline-block;margin: 0px 2px;width: 760px;">
              <el-upload
                :on-preview="handlePictureCardPreview"
                :before-remove="handleBeforeRemove"
                :on-success="handleSuccess"
                :on-error="handleError"
                :headers="headers"
                :file-list="fileList"
                :action="imagesUploadApi"
                list-type="picture-card"
                :disabled="isView"
              >
                <i class="el-icon-plus" />
              </el-upload>
              <el-dialog :append-to-body="true" :visible.sync="dialogVisible">
                <img :src="dialogImageUrl" width="100%" alt="">
              </el-dialog>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="linker">
            <el-input v-model="form.linker" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="cellphone">
            <el-input v-model="form.cellphone" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.notes" :rows="4" type="textarea" style="width: 760px;" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-show="form.state !== 100" :loading="loading" type="primary" @click="cancel">返回</el-button>
      <el-button v-show="form.state === 100" type="text" @click="cancel">取消</el-button>
      <el-button v-show="form.state === 100" :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>
<script>
import request from '@/utils/request'
import { mapGetters } from 'vuex'
import { add, edit } from '@/api/tAccident'
import { del } from '@/api/picture'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/index'
import AreaSelect from '@/components/AreaSelect'
import { isvalidPhone } from '@/utils/validate'

export default {
  components: { AreaSelect },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    isView: {
      type: Boolean,
      required: true
    },
    supThis: {
      type: Object,
      default: null
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      customerItem: [],
      devices: [],
      dialog: false,
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      pictures: [],
      loading: false,
      form: {
        id: '',
        customerId: '',
        customerName: '',
        faultDevice: '',
        faultDesc: '',
        faultPicture: '',
        reqiureTime: '',
        address: '',
        notes: '',
        linker: '',
        cellphone: '',
        inputOperator: '',
        reportTime: parseTime(new Date().getTime()),
        source: '3', // 平台
        state: 100,
        country: '',
        province: '',
        city: '',
        county: ''
      },
      rules: {
        customerName: [
          { required: true, message: '请选择客户', trigger: 'blur' }
        ],
        faultDesc: [
          { required: true, message: '请输入故障描述', trigger: 'blur' }
        ],
        faultDevice: [
          { required: true, message: '请选择故障设备', trigger: 'blur' }
        ],
        reportTime: [
          { required: true, message: '请选择报修时间', trigger: 'blur' }
        ],
        linker: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        cellphone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi'
    ])
  },
  mounted: function() {
    this.tcustmerInfoAll()
  },
  methods: {
    handleSelectArea(countryItem, provinceItem, cityItem, areaItem) {
      this.form.country = countryItem.name
      this.form.province = provinceItem.name
      this.form.city = cityItem.name
      this.form.county = areaItem.name
    },
    tcustmerInfoAll() {
      this.getAllcustmer().then(res => {
        this.customerItem = res
      })
    },
    getAllcustmer() {
      return request({
        url: 'api/tCustomerInfoAll',
        method: 'get'
      })
    },
    handleSelect(item) {
      this.devices = []
      this.form.customerName = item.customerName
      this.form.customerId = item.id
      this.form.faultDevice = ''
      this.form.address = ''
      this.getEquipment()
    },
    handleSelectDevice(id) {
      const item = this.devices.find(v => v.id === id)
      if (item) {
        this.form.address = item.address
        this.form.country = item.country
        this.form.province = item.province
        this.form.city = item.city
        this.form.county = item.county
      }
    },
    getEquipment: function() {
      const params = {
        customerId: this.form.customerId,
        pageNo: 0,
        pageSize: 9999
      }
      request({
        url: 'api/tEquipment',
        method: 'get',
        params
      }).then(res => {
        this.devices = res.content
      }).catch(err => {
        console.log(err)
      })
    },
    cancel() {
      this.resetForm()
      this.fileList = []
      this.pictures = []
      this.dialogVisible = false
      this.dialogImageUrl = ''
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        console.log(valid)
        if (valid) {
          this.loading = true
          const pictureIds = []
          this.pictures.forEach(function(data, index) {
            pictureIds.push(data.id)
          })
          this.form.faultPicture = pictureIds.join(',')
          this.fileList = []
          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
        } else {
          return false
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      this.form.reqiureTime = parseTime(this.form.reqiureTime)
      this.form.reportTime = parseTime(this.form.reportTime)
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.supThis.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.$refs['areaSelect'] && this.$refs['areaSelect'].clear()
      this.devices = []
      this.form = {
        id: '',
        customerId: '',
        customerName: '',
        faultDevice: '',
        faultDesc: '',
        faultPicture: '',
        reqiureTime: '',
        address: '',
        notes: '',
        linker: '',
        cellphone: '',
        inputOperator: '',
        reportTime: parseTime(new Date().getTime()),
        source: '3',
        state: 100,
        country: '',
        province: '',
        city: '',
        county: ''
      }
    },
    handleSuccess(response, file, fileList) {
      const uid = file.uid
      const id = response.data[0]
      this.pictures.push({ uid, id })
      console.log(this.pictures)
    },
    handleBeforeRemove(file, fileList) {
      const _this = this
      for (let i = 0; i < this.pictures.length; i++) {
        if (this.pictures[i].uid === file.uid || file.id === this.pictures[i].id) {
          del(this.pictures[i].id).then(res => {
            _this.pictures.splice(i, 1)
          })
          console.log(_this.pictures)
          return true
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    }
  }
}
</script>

<style scoped>
.input_text {
  width: 300px
}
</style>
